<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { createAdvert, updateAdvert, getAdvertDetail } from '@/api/advert/admin'
import { getAdvertPositionPageList } from '@/api/advertPosition/admin'
import { ContentWrap } from '@/components/ContentWrap'
import type { AdvertCreateOrUpdateParams, AdvertPositionOption } from '@/api/advert/types'
import { Plus } from '@element-plus/icons-vue'

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>()

// 路由和路由参数
const router = useRouter()
const route = useRoute()

// 判断是否为编辑模式
const isEdit = ref(false)

// 广告位选项
const advertPositionOptions = ref<AdvertPositionOption[]>([])

// 表单数据
const form = reactive<AdvertCreateOrUpdateParams>({
  name: '',
  status: 1,
  startTime: '',
  endTime: '',
  positionId: '',
  contentJson: '',
  sort: 0,
  remark: ''
})

// contentJson内容对象
const contentData = reactive({
  imageUrl: '',
  linkUrl: '',
  width: undefined as number | undefined,
  height: undefined as number | undefined,
  title: ''
})

// 图片上传加载状态
const imageUploadLoading = ref(false)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
  positionId: [{ required: true, message: '请选择广告位', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 加载状态
const loading = ref(false)

// 获取广告位选项
const fetchAdvertPositionOptions = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100
    }
    const response = await getAdvertPositionPageList(params)
    if (response.code === 200) {
      advertPositionOptions.value = response.data.list.map((item) => ({
        id: item.id,
        name: item.name
      }))
    } else {
      ElMessage.error(response.message || '获取广告位列表失败')
    }
  } catch (error) {
    ElMessage.error('获取广告位列表失败')
  }
}

// 获取广告详情
const fetchAdvertDetail = async (id: string) => {
  try {
    loading.value = true
    const response = await getAdvertDetail(Number(id))
    if (response.code === 200) {
      const data = response.data
      Object.assign(form, data)

      // 解析contentJson
      if (data.contentJson) {
        try {
          const content = JSON.parse(data.contentJson)
          Object.assign(contentData, content)
        } catch (e) {
          console.error('解析contentJson失败', e)
        }
      }
    } else {
      ElMessage.error(response.message || '获取广告详情失败')
    }
  } catch (error) {
    ElMessage.error('获取广告详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true

        // 组装contentJson
        form.contentJson = JSON.stringify(contentData)

        let response

        if (isEdit.value) {
          // 编辑模式
          response = await updateAdvert(form.id!, form)
        } else {
          // 新增模式
          response = await createAdvert(form)
        }

        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          router.push({ name: 'AdvertPageList', query: { refresh: '1' } })
        } else {
          ElMessage.error(response.message || (isEdit.value ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push({ name: 'AdvertPageList' })
}

// 上传图片处理
const handleImageUpload = (file: File) => {
  imageUploadLoading.value = true
  const formData = new FormData()
  formData.append('file', file)

  // 实际项目中应调用真实的上传接口
  const VITE_API_BASE_PATH = import.meta.env.VITE_API_BASE_PATH
  fetch(VITE_API_BASE_PATH + '/upload/image', {
    method: 'POST',
    body: formData
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.code === 200) {
        contentData.imageUrl = data.data.full_url
      } else {
        ElMessage.error(data.message || '图片上传失败')
      }
    })
    .catch(() => {
      ElMessage.error('图片上传失败')
    })
    .finally(() => {
      imageUploadLoading.value = false
    })

  return false
}

// 初始化
onMounted(() => {
  fetchAdvertPositionOptions()

  const id = route.params.id as string
  if (id && id !== '0') {
    isEdit.value = true
    fetchAdvertDetail(id)
  }
})
</script>

<template>
  <ContentWrap
    :title="isEdit ? '编辑广告' : '新增广告'"
    :message="isEdit ? '编辑广告信息' : '添加新的广告信息'"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 800px"
      :disabled="loading"
    >
      <el-form-item label="广告名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入广告名称" />
      </el-form-item>

      <el-form-item label="广告位" prop="positionId">
        <el-select v-model="form.positionId" placeholder="请选择广告位" style="width: 100%">
          <el-option
            v-for="item in advertPositionOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="form.startTime"
          type="datetime"
          placeholder="请选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="请选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="0"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="广告内容">
        <el-card shadow="never" style="width: 800px">
          <div style="margin-bottom: 15px">
            <el-form-item label="图片" label-width="80px" style="margin-bottom: 5px">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="handleImageUpload"
                accept="image/*"
                :loading="imageUploadLoading"
              >
                <img v-if="contentData.imageUrl" :src="contentData.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <el-input
                v-model="contentData.imageUrl"
                placeholder="图片链接"
                style="width: calc(100% - 150px); margin-left: 10px"
              />
            </el-form-item>
          </div>

          <el-form-item label="链接" label-width="80px" style="margin-bottom: 5px">
            <el-input v-model="contentData.linkUrl" placeholder="跳转链接" />
          </el-form-item>

          <div style="display: flex; gap: 15px; margin-bottom: 5px">
            <el-form-item label="宽度" label-width="80px">
              <el-input-number v-model="contentData.width" placeholder="宽度" :min="0" />
            </el-form-item>

            <el-form-item label="高度" label-width="80px">
              <el-input-number v-model="contentData.height" placeholder="高度" :min="0" />
            </el-form-item>
          </div>

          <el-form-item label="标题" label-width="80px">
            <el-input v-model="contentData.title" placeholder="标题" />
          </el-form-item>
        </el-card>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="loading">
          {{ isEdit ? '更新' : '提交' }}
        </el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<style scoped>
:deep(.el-form-item__content) {
  justify-content: flex-start;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: inline-block;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
